<?php


namespace app\http\middleware;




use app\admin\model\Staff;

use app\home\model\UserToken;
use app\Request;
use app\services\jwt\JwtService;

class MerchantCheckToken
{
    /**
     * 处理请求
     *
     * @param \think\Request $request
     * @param \Closure       $next
     * @return Response
     */
    public function handle(Request $request, \Closure $next)
    {
        if(is_null($request->header('Authorization'))){
            return error('未登录',[],'204');
        }
        if(empty($request->header('Authorization'))){
            return error('未登录',[],'204');
        }
        $token = trim(ltrim($request->header('Authorization'), 'Bearer'));
        //没有token
        if (!$token){
            return error('未登录',[],'204');
        }
        //没有找到jwt类
        $jwt=new JwtService();
        try {
            $decode=$jwt->checkToken($token);

        }catch (\Exception $e){
            return error('登录已过期，请重新登录',[],'204');
        }
        //解析token
        $decode=json_decode(json_encode($decode),true);
        if (!$decode){
            //$authInfo->delete();
            return error("登录状态有误,请重新登录",[],'204');
        }
        $authInfo = UserToken::where(['uid'=> $decode['staff_id'] ,'type' => 2])->order('effective_time','desc')->find();
        if(!$authInfo){
            return error("登录状态有误,请重新登录",[],'204');
        }
        if ($token !== $authInfo['token']){
            return error("token已过期",[],'204');
        }
        $staffModel = new Staff();
        $account  = $staffModel->where(['id' => $authInfo['uid']])->find();
        if(!$account){
            return error("登录状态有误,请重新登录",[],'204');
        }
        if($account['status'] !== 1){
            return error("账号未启用,请联系管理员",[],'204');
        }
        $account['role_id'] = $decode['role_id'];
        $account['store_id'] = $decode['store_id'];
        //$staffRoleModel = new StaffRole();
        //$role = $staffRoleModel->where(['staff_id' =>$authInfo['uid'] ])->find();
        //$account['role_id'] = $role['role_id'];
        $roleModel = new \app\admin\model\Role();
        $roleInfo = $roleModel->where(['id'=> $decode['role_id']])->find();
        $account['role_type'] = $roleInfo['type'];

        $request->staff_account = $account;
        return $next($request);
    }
}